define([ 'jquery', 'underscore', 'backbone', 'bootstrap','wysihtml5','bt-wysihtml5','BaseModule','text!templates/BlogModuleTemplate.jst'],
		function($, _, Backbone, bt,wysi,btwysi,BaseModule,BlogModuleTemplate) {
	        var blogContext={},eventsName={
	        		showPanel:"BlogModule:showPanel",
	        		refreshComment:"BlogModule:refreshComment",
	        		showBlog:"BlogModule:showBlog",
	        		newWord:"BlogModule:newWord",
	        		scrollToNewWord:"BlogModule:scrollToNewWord"
	        		}
	        ;
	        
	        _.extend(blogContext,Backbone.Events);
	        
	        var blogModuleUrl={
	        		blog:BaseModule.WebRoot+"blog",
	        		blogComment:BaseModule.WebRoot+"blogComment",
	        		translateData:BaseModule.WebRoot+"translateData"
	        };
	        var BlogRouter=Backbone.Router.extend({
	        	routes:{
	        		"BlogModule/blog/newBlog":"newBlog",
	        		"BlogModule/blog/bloglist":"blogList",
	        		"BlogModule/blog/openBlog/:blogId":"openBlog"
	        		
	        	},
	        	newBlog:function(){
	        		blogContext.trigger(eventsName.showPanel,"newBlog");
	        	},
	        	blogList:function(){
	        		blogContext.trigger(eventsName.showPanel,"blogList");
	        	},
	        	openBlog:function(blogId){
	        		blogContext.trigger(eventsName.showPanel,"openBlog",blogId);
	        	}
	        	
	        });
			var BlogModule = Backbone.View.extend({
				template:_.template(BlogModuleTemplate),
				initialize : function() {
					Backbone.Events.on("shiftModule",this.open,this);
					this.sideBar=new SideBarView();
					this.listBlogPanel=new ListBlogView();
					this.createBlog=new CreateBlogView();
					this.blogShow=new BlogShowView();
					this.router =new BlogRouter();
					blogContext.on(eventsName.showPanel,this.show,this);
				},
				render:function(){
					if(this.rendered){return this;}
					$(this.el).html(this.template({'tempId':'BaseFrameWork','data':null}));
					this.$('#sidebarWrapper').html(this.sideBar.render().el);
					this.$('#centerWrapper').append(this.listBlogPanel.render().el);
					this.$('#centerWrapper').append(this.createBlog.el);
					this.$('#centerWrapper').append(this.blogShow.el);
					this.rendered=true;
					return this;
				},
				open:function(name){
					name == "blog" ? this.render().$el.fadeIn(): this.$el.hide();
				},
				show:function(name){
					$('#topNavUL>li').removeClass("active");
			 		$('#topNavUL>li:eq(2)').addClass("active")
			 		Backbone.Events.trigger("shiftModule","blog");
				}
			});

			var SideBarView=Backbone.View.extend({
				tagName:"div",
				template:_.template(BlogModuleTemplate),
				events:{
				},
				initialize:function(){
				},
				render:function(){
					$(this.el).html(this.template({'tempId':'BlogSidebar','data':null}));
					return this;
				}
				
			});
			
			
			var ListBlogView=Backbone.View.extend({
				tagName:"div",
				template:_.template(BlogModuleTemplate),
				initialize: function(){
					this.blogList=new BlogList();
					this.blogList.bind('add',this.addOne,this);
					this.blogList.bind('reset',this.addAll,this);
					blogContext.on(eventsName.showPanel,this.open,this);
			    },
			    render:function(){
			    	$(this.el).html(this.template({'tempId':'BlogIist','data':null}));
			    	this.blogList.fetch({
			    		url:blogModuleUrl.blog,
			    		error:function(){
			    		alert('error');
			    	}});
			    	return this;
			    },
				open:function(viewName){
					(viewName=="blogList") ? this.$el.show():this.$el.hide();
				},
			    addOne:function(iModel){
			    	var itemView=new ListBlogItemView({model:iModel});
			    	this.$("ul").append(itemView.render().el);
			    },
			    addAll:function(){
			    	this.blogList.each(this.addOne,this);
			    }
			});
			var ListBlogItemView=Backbone.View.extend({
				 tagName:"li",
			     template:_.template(BlogModuleTemplate),
			     initialize:function(){
			     },
			     render:function(){
			    	 this.$el.html(this.template({'tempId':'BlogIistItem','data':this.model.toJSON()}));
			    	 return this;
			     }
			});
			
			var BlogModel=BaseModule.BaseModel.extend({
            	urlRoot:blogModuleUrl.blog,
				validate:function(attrs){
					 if(attrs.title == ''){
						   return "title can not be null";
					   }
					   if(attrs.blogContent == ''){
						   return "solution can not be null";
					   }
				}
			});
			var BlogList=BaseModule.BaseCollection.extend({
				model:BlogModel,
				initialize:function(){
				}
				
			});
			
			var CreateBlogView=Backbone.View.extend({
				tagName:"div",
				 template:_.template(BlogModuleTemplate),
				 initialize: function (){
					 blogContext.on(eventsName.showPanel,this.open,this);
				 },
				 events:{
					 'click #submitBlogBtn':"submitBlog"
				 },
				 render:function(){
					$(this.el).html(this.template({'tempId':'CreateBlog','data':null}));
					$('#blogContent').css({"width":730,'height':400});
					$('#blogContent').wysihtml5(
					  {
						  "font-styles": true, //Font styling, e.g. h1, h2, etc. Default true
							"emphasis": true, //Italics, bold, etc. Default true
							"lists": true, //(Un)ordered lists, e.g. Bullets, Numbers. Default true
							"html": false, //Button which allows you to edit the generated HTML. Default false
							"link": true, //Button to insert a link. Default true
							"image": true, //Button to insert an image. Default true,
							"color": true //Button to change color of font
					  }		
					);
					return this;
				 },
				 open:function(viewName){
					 (viewName=="newBlog") ? $(this.render().el).show():this.$el.hide();
				 },
				 submitBlog:function(){
					 var curEL=this.el;
					    this.$('[name=_wysihtml5_mode]').remove();
						var form=this.$('form');
						this.model=new BlogModel();
						this.model.save(form.serializeJSON(),{
							url:blogModuleUrl.blog,
							success:function(model){
							$('#cancelBtn').click();
							alert("saved ok!");
							blogContext.trigger(eventsName.showBlog,model);
						}});
				}
			 });
			
			var BlogShowView=Backbone.View.extend({
				 tagName:"div",
				 template:_.template(BlogModuleTemplate),
				 initialize: function (){
					 blogContext.on(eventsName.showPanel,this.openWithId,this);
					 blogContext.on(eventsName.showBlog,this.openWithModel,this);
					 this.addCommentView=new AddCommentView();
					 this.commList=new CommentListView();
					 _.bindAll(this,'translate');
					 this.$el.dblclick(this.translate);
					 this.newWordListVew=new TranslateListView();
				 },
				 render:function(){
					 $(this.el).html(this.template({'tempId':'BlogView','data':this.model.toJSON()}));
					 this.addCommentView.model=this.model;
					 this.commList.model=this.model;
					 $(this.el).append(this.addCommentView.render().el);
			    	 $(this.el).append(this.commList.render().el);
			    	 this.newWordListVew.blogId=this.model.get("id");
			    	 $('#rightWrapper').html(this.newWordListVew.render().el);
					 return this;
				 },
				 openWithModel:function(model){
					 blogContext.trigger(eventsName.showPanel,"hideOthers");
						 this.model=model;
						 $(this.render().el).show(); 
				 },
				  openWithId:function(viewName,id){
					  if(viewName=="openBlog"){
						  var cur=this;
						  this.model=new BlogModel({'id':id});
						  this.model.fetch({
							    success:function(){
									  $(cur.render().el).show();  
								  }
							  });
						 
					  }else{
						  this.$el.hide();
					  }
				  },
				  translate:function(){
					  var selectText=new String();
					  if(document.selection){
						  selectText=document.selection();
					  }else if(window.getSelection){
						  selectText=window.getSelection();
					  }
					  if(selectText != null && selectText != "" && $.trim(selectText) != ""){
						  blogContext.trigger(eventsName.newWord,selectText.toString());
					  }
					 }
			});
			
			var TranslateDataModel=BaseModule.BaseModel.extend({
            	urlRoot:blogModuleUrl.translateData,
            	active:false
			});
			
			var BlogTranslateMapModel=BaseModule.BaseModel.extend({
            	urlRoot:blogModuleUrl.translateData,
				validate:function(attrs){
					 if(attrs.blogId == ''){
						   return "blogId can not be null";
					   }
					   if(attrs.translateData.sourceText == ''){
						   return "Source Text can not be null";
					   }
				}
			});
			var TranslateDataList=BaseModule.BaseCollection.extend({
				model:TranslateDataModel,
				blogId:0,
				url:function(){
					return blogModuleUrl.translateData+"/"+this.blogId;
				},
				checkDuplicate:function(text){
					var result=false;
					this.each(function(model){
						if($.trim(model.get("sourceText")).toLowerCase() == $.trim(text).toLowerCase()){
							if(!model.get("active")){
								model.set({"active":true});
							}
							result= true;
						}else{
							if(model.get("active")){
								model.set({"active":false});
							}
						}
					});
					return result;
				}
			});
			var TranslateListView=Backbone.View.extend({
				tagName:"div",
				className:"wordListDiv",
				template:_.template(BlogModuleTemplate),
				blogId:0,
				initialize: function(){
					this.newWordList=new TranslateDataList();
					this.newWordList.bind("add",this.addOne,this);
					this.newWordList.bind("reset",this.addAll,this);
					blogContext.on(eventsName.newWord,this.addTranslateData,this);
					blogContext.on(eventsName.scrollToNewWord,this.scrollTop,this);
				},
				render:function(){
					this.$el.html(this.template({'tempId':'translateList','data':null}));
					this.newWordList.blogId=this.blogId;
					this.newWordList.fetch();
					return this;
				},
				addTranslateData:function(sourceText){
					var cur=this;
					var handleResult=function(data){
						  console.log(data);
						   alert(data);
					  };
					  
					 if(!cur.newWordList.checkDuplicate(sourceText)){
					 $.ajax({
			             type: "get",
			             async: false,
			             url: "http://fanyi.youdao.com/openapi.do?keyfrom=pizahouse&key=1517817920&type=data&doctype=jsonp&callback=handleResult&version=1.1&q="+sourceText,
			             dataType: "jsonp",
			             jsonp: "callback",
			             jsonpCallback:"handleResult",
			             success: function(json){
			                if(json.errorCode == 0){
			                	// alert(json.translation);
			                	 var newWordData={blogId:cur.blogId,
			                			translateData:{
			                				'sourceText':sourceText,
			                				'translatedText':json.translation.toString()
			                			}
			                	 };
			                	var newData=new BlogTranslateMapModel(newWordData);
			                	newData.save();
			                	var translateData=new TranslateDataModel(newData.get("translateData"));
			                	cur.newWordList.add(translateData);
			                }
			             },
			             error: function(){
			                 alert('fail');
			             }
			         });
				 }
				},
				addOne:function(tempModel){
					var newWordView=new NewWordView({model:tempModel});
					this.$('dl').append(newWordView.render().el);
				},
				addAll:function(){
					this.newWordList.each(this.addOne,this);
				},
				scrollTop:function(position){
					this.$el.scrollTop(position.top);
				}
			});
			var NewWordView=Backbone.View.extend({
				tagName:"div",
				template:_.template(BlogModuleTemplate),
				initialize:function(){
					this.model.bind("change:active",this.active,this);
				},
				render:function(){
					this.$el.html(this.template({'tempId':'translateListItem','data':this.model.toJSON()}));
					return this;
				},
				active:function(){
					if(this.model.get("active")){
						this.$el.css("background-color","rgba(184, 236, 168, 0.99)");
						blogContext.trigger(eventsName.scrollToNewWord,this.$el.position());
					}else{
						this.$el.css("background-color","");
					}
					
				}
			});
			
			
			var AddCommentView=Backbone.View.extend({
				tagName:"div",
				template:_.template(BlogModuleTemplate),
				events:{
				  'click .textarea':"focusArea",
				  'click [type=button]':"submitComment"
				},
				initialize: function(){
				},
				render:function(){
					$(this.el).html(this.template({'tempId':'AddComment','data':null}));
					return this;
				},
				focusArea:function(e){
					e.stopPropagation();
					this.textAreaObj=$(e.srcElement).wysihtml5();
					
				},
				submitComment:function(e){
					var textArea=this.textAreaObj;
					var newComment=new CommentModel();
					newComment.set({'blogId':this.model.get("id")});
					newComment.set({'userId':9});
					newComment.set({'content':$(this.textAreaObj).val()});
					newComment.save({
						success:function(){
							$(textArea).data().wysihtml5.editor.clear();
							blogContext.trigger(namespace.refreshComment);
						},
						error:function(){
							alert('error when save comment');
						}
					});
				}
			});
			var CommentModel=BaseModule.BaseModel.extend({
			  	urlRoot:blogModuleUrl.blogComment
			});
			
			var CommentList=BaseModule.BaseCollection.extend({
				model:CommentModel
			});
			
			var CommentView=Backbone.View.extend({
				tagName:"div",
				template:_.template(BlogModuleTemplate),
				initialize: function (){
					this.model.bind("destroy",this.remove,this);
				 },
				 render:function(){
					 $(this.el).html(this.template({'tempId':'Comment','data':this.model.toJSON()}));
					 return this;
				 },
				 remove:function(){
					 $(this.el).remove();
				 }
			});
            var CommentListView=Backbone.View.extend({
            	tagName:"div",
            	template:_.template(BlogModuleTemplate),
				initialize:function(){
					 this.commList=new CommentList();
					 this.commList.bind("add",this.addOne,this);
					 this.commList.bind("reset",this.addAll,this);
//					 this.commList.fetch({url:blogModuleUrl.blogComment+"/"+this.model.get("blogId")});
				 },
				 render:function(){
					 $(this.el).html(this.template({'tempId':'CommentList','data':null}));
					 this.refresh();
					 return this;
				 },
				 addOne:function(cModel){
					 var commView=new CommentView({model:cModel});
					this.$('ul').append(commView.render().el);
				 },
				 addAll:function(){
					 this.$('ul').empty();
					 this.commList.each(this.addOne,this); 
				 },
				 refresh:function(){
					 this.commList.fetch({url:blogModuleUrl.blogComment+"/"+this.model.get("id")});
				 }
			});
            
			return BlogModule;
		});